//
//  EJSPayOrderViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/19.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSPayOrderViewController.h"
#import "EJSOffLinePayForOrderViewController.h"

#import "EJSOfflinePayRequest.h"
#import "EJSPayForOrderRequest.h"
#import "EJSPreparePayForOrderRequest.h"
#import "EJSOrderModel.h"
#import "BraintreeCore.h"
#import "BraintreeDropIn.h"
#import "EJSOrderListViewController.h"
#import "BraintreePayPal.h"
#import <BraintreeCard.h>
#import <BTAPIClient.h>

#if (YiPinShangCheng == 1)//一品商城
#import <Stripe.h>
#import "StripeApiClient.h"
#endif

#import "EJSPayWebViewController.h"
#import "EJSUserBalanceRequest.h"

#import "EJSUnionPayRequest.h"
#import <BTThreeDSecureRequest.h>

/*
 1 => '线下支付',
 2 => '货到付款+3欧元',
 3 => '信用卡支付',
 4 => '支付宝-微信（当天中国银行汇率',
 5 => 'POSTA PAY   汇款',
 */

@interface EJSPayOrderViewController () <BTViewControllerPresentingDelegate,BTAppSwitchDelegate,BTCardFormViewControllerDelegate,BTDropInControllerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *totalPayLabel;
@property (weak, nonatomic) IBOutlet UIButton *paymentButton;
@property (weak, nonatomic) IBOutlet UILabel *balanceLabel;

@property (weak, nonatomic) IBOutlet UIView *payMethodOneCover;
@property (weak, nonatomic) IBOutlet UIView *payMethodTwoCover;
@property (weak, nonatomic) IBOutlet UIView *payMethodThreeCover;
@property (weak, nonatomic) IBOutlet UIButton *payMethodOneBtn;
@property (weak, nonatomic) IBOutlet UIButton *payMethodTwoBtn;
@property (weak, nonatomic) IBOutlet UIButton *payMethodThreeBtn;
@property (weak, nonatomic) IBOutlet UILabel *payMethodOneLabel;
@property (weak, nonatomic) IBOutlet UILabel *payMethodTwoLabel;
@property (weak, nonatomic) IBOutlet UILabel *payMethodThreeLabel;

@property (strong, nonatomic) UIButton *selectedButton;
@property (assign, nonatomic) NSInteger payMethod;//0 余额 1 信用卡 2 线下支付
@property (strong, nonatomic) EJSUserBalanceModel* balanceModel;
@property (strong, nonatomic) EJSPreparePayForOrderModel *preparePayForModel;

@end

@implementation EJSPayOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"订单支付";
    _payMethod = -1;
    [self reloadCanUserPayMothed];
    
    self.totalPayLabel.text = [NSString stringWithFormat:@"€ %@",self.orderModel.totalAmount];
//    [self getPreparePayInfo];
    [self getUserBalance];
    
}

#pragma mark - 获取可用的支付方式
- (void)reloadCanUserPayMothed {
    
    self.payMethodOneCover.hidden = YES;
    self.payMethodTwoCover.hidden = YES;
    self.payMethodThreeCover.hidden = YES;
    for (int i = 0; i < self.orderModel.paymentMethod.count; i++) {
        if (i > 2) {
            break;
        }
        
        NSString *payMethodStr;
        NSString *payFlag = [self.orderModel.paymentMethod objectAtIndex:i];
        
        switch (payFlag.intValue) {
            case 1:
                payMethodStr = @"自取";//线下付款
                break;
            case 2:
                payMethodStr = @"货到付款（+ 3.00 euro）";
                break;
            case 3:
                payMethodStr = @"信用卡支付";
                break;
            case 4:
                payMethodStr = @"支付宝-微信（当天中国银行汇率)";
                break;
            case 5:
                payMethodStr = @"POSTA PAY 汇款";
                break;
            default:
                break;
        }
        
        
        if (i == 0) {
            self.payMethodOneCover.hidden = NO;
            self.payMethodOneLabel.text = payMethodStr;
            self.payMethodOneBtn.tag = payFlag.intValue;
        }else if (i == 1) {
            self.payMethodTwoCover.hidden = NO;
            self.payMethodTwoLabel.text = payMethodStr;
            self.payMethodTwoBtn.tag = payFlag.intValue;
        }else {
            self.payMethodThreeCover.hidden = NO;
            self.payMethodThreeLabel.text = payMethodStr;
            self.payMethodThreeBtn.tag = payFlag.intValue;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//MARK: - 获取用户余额
- (void)getUserBalance{
    FlyWeakSelf
    [[EJSUserBalanceRequest new] asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        EJSUserBalanceModel *model = response.data;
        self.balanceModel = model;
        weakSelf.balanceLabel.text = [NSString stringWithFormat:@"%@ €",model.money];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)getPreparePayInfo{
    EJSPreparePayForOrderRequest *req = [EJSPreparePayForOrderRequest new];
    req.orderId = self.orderModel.orderId;
    req.paymentMethod = @"redsys";
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.preparePayForModel = response.data;
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage: response.message];
    }];
}

- (void)setPreparePayForModel:(EJSPreparePayForOrderModel *)preparePayForModel{
    if (_preparePayForModel != preparePayForModel) {
        _preparePayForModel = preparePayForModel;
        self.totalPayLabel.text = [NSString stringWithFormat:@"€ %@",_preparePayForModel.amount];
    }
}

- (IBAction)selectPayMethodAction:(UIButton *)sender {
    if(_selectedButton == sender){
        return;
    }
    sender.selected = YES;
    _selectedButton.selected = NO;
    _selectedButton = sender;
    _payMethod = _selectedButton.tag;
    
    if (_payMethod == 2) {
        self.totalPayLabel.text = [NSString stringWithFormat:@"€ %.2f",self.orderModel.totalAmount.doubleValue+3.00];
    }else {
        self.totalPayLabel.text = [NSString stringWithFormat:@"€ %@",self.orderModel.totalAmount];
    }
    
}

- (IBAction)payAction:(UIButton *)sender {
    
    if (self.orderModel.paymentMethod.count == 0) {
        [[HUDHelper sharedInstance] tipMessage:@"该店铺还未设置支付方式"];
        return;
    }
    NSString *payMethodString = [NSString stringWithFormat:@"%ld",(long)_payMethod];
        
    if([payMethodString isEqualToString:@"-1"]){//未选择
        [[HUDHelper sharedInstance] tipMessage:@"请选择支付方式"];
    }else if([payMethodString isEqualToString:@"3"]){//信用卡
        if(_preparePayForModel.redsys){
            EJSPayWebViewController *payWebVC = [[EJSPayWebViewController alloc] init];
            payWebVC.redsys = _preparePayForModel.redsys;
            [self.navigationController pushViewController:payWebVC animated:YES];
            return;
        }
        [self payForCard];
    }else{//其他支付方式
        [self unionPayMethod:payMethodString];
    }
    
/*
    switch (_payMethod) {
        case -1:
            [[HUDHelper sharedInstance] tipMessage:@"请选择支付方式"];
            return;
        case 0://余额支付
            [self payForBalance];
            break;
        case 1: //线下支付
            [self payForOffline];
            break;
        case 2:// 货到付款
            [self payForPayTo];
            break;
        case 3://信用卡付款
            if(_preparePayForModel.redsys){
                EJSPayWebViewController *payWebVC = [[EJSPayWebViewController alloc] init];
                payWebVC.redsys = _preparePayForModel.redsys;
                [self.navigationController pushViewController:payWebVC animated:YES];
                return;
            }
            [self payForCard];
            break;
        case 4://支付宝-微信
            [[HUDHelper sharedInstance] tipMessage:@"未接入的支付方式"];
            break;
        case 5://posta pay
            [self postaPay];
            break;
        default: //-1
            [[HUDHelper sharedInstance] tipMessage:@"未定义的支付方式"];
            break;
    }
 */
    
}

#pragma mark - 支付方式


#pragma mark 信用卡支付
- (void)payForCard {
    
    [[HUDHelper sharedInstance] syncLoading];
    BTAPIClient *client = [[BTAPIClient alloc] initWithAuthorization:self.preparePayForModel.clientToken];
    [client fetchOrReturnRemoteConfiguration:^(BTConfiguration * _Nullable configuration, NSError * _Nullable error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                NSArray *supportedCardTypes = [configuration.json[@"creditCards"][@"supportedCardTypes"] asArray];
                NSMutableArray *paymentOptionTypes = [NSMutableArray new];
                for (NSString *supportedCardType in supportedCardTypes) {
                    BTUIKPaymentOptionType paymentOptionType = [BTUIKViewUtil paymentOptionTypeForPaymentInfoType:supportedCardType];
                    if (paymentOptionType != BTUIKPaymentOptionTypeUnknown) {
                        [paymentOptionTypes addObject: @(paymentOptionType)];
                    }
                }
                
                BTDropInRequest *request = [[BTDropInRequest alloc] init];
                request.threeDSecureRequest.amount = [NSDecimalNumber decimalNumberWithString:self.preparePayForModel.amount];
//                request.amount = self.preparePayForModel.amount;
                BTAPIClient *braintreeClient = [[BTAPIClient alloc] initWithAuthorization:self.preparePayForModel.clientToken];
                BTCardFormViewController *cardVC = [[BTCardFormViewController alloc] initWithAPIClient:braintreeClient request:request];
                cardVC.delegate = self;
                cardVC.supportedCardTypes = paymentOptionTypes;
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cardVC];
                [self presentViewController:nav animated:YES completion:nil];
            } else {
               
            }
        });
    }];
}
- (void)cardTokenizationCompleted:(BTPaymentMethodNonce * _Nullable )tokenizedCard error:(NSError * _Nullable )error sender:(BTCardFormViewController *) sender{
    dispatch_async(dispatch_get_main_queue(), ^{
            if (tokenizedCard != nil) {
                [self payForOrder:tokenizedCard.nonce];
            } else if (error == nil) {
                [[HUDHelper sharedInstance] tipMessage:@"用户取消"];
            }
            [sender dismissViewControllerAnimated:YES completion:nil];
    });
}
- (void)reloadDropInData{
    
}

/*
 #pragma mark 线下付款，暂时直接下单成功，隐藏Offline
 - (void)payForOffline {
     EJSOfflinePayRequest *req = [EJSOfflinePayRequest new];
     req.orderId = self.orderModel.orderId;
     [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
         if(response.success){
             [HUDHelper alertTitle:@"提示" message:@"下单成功" cancel:@"确定" action:^{
                 [self.navigationController popToRootViewControllerAnimated:YES];
             }];
         }else{
             [HUDHelper alertTitle:@"提示" message:response.message cancel:@"确定" action:^{
             }];
         }
         
     } failHandler:^(BaseResponse *response) {
         [HUDHelper alertTitle:@"提示" message:response.message cancel:@"确定" action:^{
         }];
     }];
 }
 
#pragma mark 余额 支付
- (void)payForBalance {
    if (self.balanceModel.money.doubleValue < self.preparePayForModel.amount.doubleValue) {
        [[HUDHelper sharedInstance]tipMessage: NSLocalizedString(@"余额不足", nil)];
    }else {
        [self payForOrder:@""];
    }
}

#pragma mark Paypal支付
- (void)payForPaypal {
    [[HUDHelper sharedInstance] syncLoading];
    BTAPIClient *braintreeClient = [[BTAPIClient alloc] initWithAuthorization:self.preparePayForModel.clientToken];
    BTPayPalDriver *payPalDriver = [[BTPayPalDriver alloc] initWithAPIClient:braintreeClient];
    payPalDriver.viewControllerPresentingDelegate = self;
    payPalDriver.appSwitchDelegate = self; // Optional
    
    // Start the Vault flow, or...
    [payPalDriver authorizeAccountWithCompletion:^(BTPayPalAccountNonce *tokenizedPayPalAccount, NSError *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [self payForOrder:tokenizedPayPalAccount.nonce];
    }];
    
    BTPayPalRequest *request = [[BTPayPalRequest alloc] initWithAmount:self.preparePayForModel.amount];
    [payPalDriver requestOneTimePayment:request
                             completion:^(BTPayPalAccountNonce *tokenizedPayPalAccount, NSError *error) {
                                 [[HUDHelper sharedInstance] syncStopLoading];
                                [self payForOrder:tokenizedPayPalAccount.nonce];
                             }];
}

#pragma mark POSTA Pay

-(void)postaPay{
    EJSPostaPayRequest *req = [EJSPostaPayRequest new];
    req.orderId = self.orderModel.orderId;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:@"下单成功"];
        EJSOrderListViewController *orderVC = [[EJSOrderListViewController alloc] init];
        orderVC.orderType = @"2";
        [self.navigationController pushViewController:orderVC animated:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } failHandler:^(BaseResponse *response) {
        EJSOrderListViewController *orderVC = [[EJSOrderListViewController alloc] init];
        orderVC.orderType = @"1";
        [self.navigationController pushViewController:orderVC animated:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }];

}

#pragma mark - 货到付款
//
- (void)payForPayTo {
    EJSPaytoPayRequest *req = [EJSPaytoPayRequest new];
    req.orderId = self.orderModel.orderId;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:@"下单成功"];
        EJSOrderListViewController *orderVC = [[EJSOrderListViewController alloc] init];
        orderVC.orderType = @"2";
        [self.navigationController pushViewController:orderVC animated:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } failHandler:^(BaseResponse *response) {
        EJSOrderListViewController *orderVC = [[EJSOrderListViewController alloc] init];
        orderVC.orderType = @"1";
        [self.navigationController pushViewController:orderVC animated:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }];

}
*/


#pragma mark - 最新支付方式 2020.05.21
- (void)payForOrder:(NSString *)nonce{
    EJSPayForOrderRequest *req = [EJSPayForOrderRequest new];
    req.nonce = nonce;
    req.orderId = self.preparePayForModel.orderId;
    req.amount = self.preparePayForModel.amount;
    req.paymentMethod = @"money";
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:@"支付成功"];
        EJSOrderListViewController *orderVC = [[EJSOrderListViewController alloc] init];
        orderVC.orderType = @"2";
        [self.navigationController pushViewController:orderVC animated:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message delay:1 completion:^{
            EJSOrderListViewController *orderVC = [[EJSOrderListViewController alloc] init];
            orderVC.orderType = @"1";
            [self.navigationController pushViewController:orderVC animated:YES];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    }];
}

//除了信用卡之外的支付方式
-(void)unionPayMethod:(NSString*)method{
    EJSUnionPayRequest *req = [EJSUnionPayRequest new];
    req.orderId = self.orderModel.orderId;
    req.pay_method = method;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:@"下单成功"];
        EJSOrderListViewController *orderVC = [[EJSOrderListViewController alloc] init];
        orderVC.orderType = @"2";
        [self.navigationController pushViewController:orderVC animated:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } failHandler:^(BaseResponse *response) {
        EJSOrderListViewController *orderVC = [[EJSOrderListViewController alloc] init];
        orderVC.orderType = @"1";
        [self.navigationController pushViewController:orderVC animated:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }];
}

#pragma mark - BTViewControllerPresentingDelegate

// Required
- (void)paymentDriver:(id)paymentDriver
requestsPresentationOfViewController:(UIViewController *)viewController {
    [self presentViewController:viewController animated:YES completion:nil];
}

// Required
- (void)paymentDriver:(id)paymentDriver
requestsDismissalOfViewController:(UIViewController *)viewController {
    [viewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - BTAppSwitchDelegate
// Optional - display and hide loading indicator UI
- (void)appSwitcherWillPerformAppSwitch:(id)appSwitcher {
    [[HUDHelper sharedInstance] syncLoading];
}

- (void)appSwitcherWillProcessPaymentInfo:(id)appSwitcher {
    [[HUDHelper sharedInstance] syncStopLoading];
}

@end
